package com.ChengXiZi.service.impl;

import com.ChengXiZi.constant.MessageConstant;
import com.ChengXiZi.constant.StatusConstant;
import com.ChengXiZi.dto.SysadminLoginDto;
import com.ChengXiZi.entity.User;
import com.ChengXiZi.exception.AccountLockedException;
import com.ChengXiZi.exception.AccountNotAllowedException;
import com.ChengXiZi.exception.AccountNotFoundException;
import com.ChengXiZi.exception.PasswordErrorException;
import com.ChengXiZi.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class SysadminServiceImpl implements com.ChengXiZi.service.SysadminService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 系统管理员登录
     * @param sysadminLoginDto
     * @return
     */
    @Override
    public User login(SysadminLoginDto sysadminLoginDto) {

        if(sysadminLoginDto.getIdentity() != 2) {
            //账号类型不允许
            throw new AccountNotAllowedException(MessageConstant.ACCOUNT_NOT_ALLOWED);
        }

        String username = sysadminLoginDto.getUsername();
        String password = sysadminLoginDto.getPassword();

        //1、根据用户名查询数据库中的数据(user实际为系统管理员)
        User user = userMapper.getByUsername(username);

        //2、处理各种异常情况（账户不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //对密码进行MD5加密，而后进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if (user.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        return user;
    }

    /**
     * 封禁普通用户账号
     * @param status
     * @param id
     * @return
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //使用User对象，实现动态更新
        User user = User.builder()
                .status(status)
                .id(id)
                .build();
        userMapper.update(user);
    }
}
